<template>
    <div class="app-container-flex">
        <NewFullScreen v-model="showDialog" :title="title" :needReturn="!flowFormType" @returnBack="$emit('returnModify')">
            <template v-slot:full-button>
                <el-button @click="saveAndSubmit()" v-if="!id && $permission('purchPlan:saveAndSubmit') && !flowFormType">保存并提交</el-button>
                <el-button v-if="!flowFormType" @click="save()">保存</el-button>
            </template>
            <div class="model-panel">
                <div class="model-panel-title">
                    <p>{{ $t('basic_information') }}</p>
                </div>
                <div class="model-panel-body">
                    <!-- form -->
                    <PageForm class="paddingBox order-model-formBox flex_wrap_start_start" v-model:ref-obj="formInfo.ref"
                        :disabled="formInfo.disabled" v-model:data="formInfo.data" :field-list="formInfo.fieldList"
                        :rules="formInfo.rules" :label-width="formInfo.labelWidth" @handleEvent="changeHandle">

                        <template v-slot:form-rangeIdValue>
                            <el-input v-if="isDisabled" type="input" :disabled="true" placeholder="请选择部门"
                                v-model="formInfo.data.rangeIdValue">

                            </el-input>
                            <el-input v-else class="not-mongolia" type="input" :disabled="true" placeholder="请选择部门"
                                v-model="formInfo.data.rangeIdValue">
                                <template #append>
                                    <el-icon @click="openDeptWindow">
                                        <MoreFilled />
                                    </el-icon>
                                </template>
                            </el-input>
                        </template>
                    </PageForm>
                </div>
            </div>

            <div class="model-panel" v-if="formInfo.data.planDimension == '2'">
                <div class="model-panel-title">
                    <Tooltip :text="$t('detailInfo')"></Tooltip>
                </div>
                <div class="model-panel-body">
                    <!-- 条件栏 -->
                    <NewPageFilter v-model:query="filterInfo.query" :filter-btn="filterInfo.list">
                        <template v-slot:filter-addProduct>
                            <el-button :disabled="isDisabled ? true : false"
                                @click="addProduct()">添加产品</el-button>
                        </template>
                        <template v-slot:filter-removeProduct>
                            <el-button :disabled="isDisabled ? true : !canRemoveProduct"
                                @click="removeProduct">删除产品</el-button>
                        </template>
                    </NewPageFilter>
                    <div class="flex_full_item">
                        <!-- 表格 -->
                        <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                            <PageTable :refresh="tableInfo.refresh" :init-curpage="tableInfo.initCurpage"
                                v-model:data="tableInfo.data" :pager="false" :summary="true"
                                :summaryFieldList="tableInfo.summaryFieldList" v-model:query="filterInfo.query"
                                :field-list="tableInfo.fieldList" :handle="isDisabled ? '':tableInfo.handle" :isDynamic="true"
                                @handleEvent="handleEvent">
                                <template v-slot:col-planNumber="scope">
                                    <el-form-item class="margin-bottom">
                                        <div class="page-table-input-number-wrapper">
                                            <div class="page-table-input-number-left">
                                                <div class="page-table-input-number-item">
                                                    <el-form-item>
                                                        <el-input-number style="width: 100%; margintop: 18px"
                                                            v-model.lazy="scope.row.planNumber" clearable
                                                            controls-position="right" :precision="scope.row.qtyOperateMode === 0 ||
                                                                scope.row.qtyOperateMode === 2
                                                                ? 0
                                                                : systemConfig.qty_show_precision
                                                                " @change="
                                                                changeLargeAndAmount(
                                                                    $event,
                                                                    `data.${scope.$index}.planNumber`
                                                                )
                                                                " :min="0" :max="99999999" />
                                                    </el-form-item>
                                                    <div class="PageTable-input-number-item-unite">
                                                        {{ scope.row.unitName }}
                                                    </div>
                                                </div>
                                                
                                            </div>
                                        </div>
                                    </el-form-item>
                                </template>
                                <template v-slot:col-planAmount="scope">
                                     <el-form-item>    
                                        <el-input-number v-model="scope.row.planAmount" controls-position="right"
                                            style="width: 100%; margintop: 18px"
                                            :precision="systemConfig.price_precision" :step="1" :min="0"
                                            :max="999999999999999" @change="
                                                changeLargeAndAmount($event, `data.${scope.$index}.planAmount`)
                                                " />
                                    </el-form-item>
                                </template>
                            </PageTable>
                        </el-form>
                    </div>
                </div>
            </div>
        </NewFullScreen>
        <NewSelectProduct v-if="productInfo.visible" v-model:showDialog="productInfo.visible"
            v-model:query="productInfo.query.queryMap" :query-params="productInfo.query.queryParams"
            :tableKey="productInfo.tableKey" :showPrice="$permission('purchTemplate:price')" @callback="selectProduct" />
        <SelectDept v-if="selectDeptInfo.visible" v-model:showDialog="selectDeptInfo.visible" :checkBox="true"
            :highlightRow="false" :saveEmpty="true" :checkedList="selectDeptInfo.checkedList" v-model:query="selectDeptInfo.query" @callback="selectDeptCallback" />
    </div>
</template>
  
<script setup>
import {
    createPurchPlan,
    updatePurchPlan,
    getPurchPlanById,
    getPurchProductDetail,
    saveAndSubmitPurchPlan,
    submitPurchPlan
} from '@/api/purch.js'
import moment from 'moment'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const store = useStore()
const props = defineProps({
    visible: {
        type: Boolean,
        default: false,
    },
    title: {
        type: String,
        default: () => {
            return ''
        },
    },
    id: {
        type: [String, Number],
    },
    isDisabled: {
        type: Boolean,
        default: false
    },
    flowFormType: {
        type: String,
        default: ''
    }
})
const systemConfig = ref(store.state.permission.systemConfig)
const formRefs = ref([])
const formInfo = ref({
    ref: null,
    data: {
        planCycle: '1',
        planDimension: '1',
        planRange: '1',
        criticalValue: 80
    },
    fieldList: [
        { label: '计划名称', value: 'planName', type: 'input', maxlength: 32, disabled: props.isDisabled },
        {
            label: '计划周期',
            value: 'planCycle',
            type: 'select-model',
            code: 'plan_cycle',
            event: 'planCycle',
            disabled: props.isDisabled
        },
        {
            label: '年度',
            value: 'planYear',
            type: 'date',
            dateType: 'year',
            valueFormat: 'YYYY',
            event: 'planYear',
            disabled: props.isDisabled
        },
        {
            label: '季度',
            value: 'planQuarter',
            type: 'select-model',
            code: 'quarter',
            show: false,
            checkDefault: false,
            event: 'planQuarter',
            disabled: props.isDisabled
        },
        {
            label: '月度',
            value: 'planMonth',
            type: 'select-model',
            code: 'month',
            show: false,
            checkDefault: false,
            event: 'planMonth',
            disabled: props.isDisabled
        },
        {
            label: '计划开始日期',
            value: 'planStartDate',
            type: 'date',
            dateType: 'date',
            show: true,
            disabled: true,
        },
        {
            label: '计划截止日期',
            value: 'planEndDate',
            type: 'date',
            dateType: 'date',
            show: true,
            disabled: true,
        },
        {
            label: '计划维度',
            value: 'planDimension',
            type: 'select-model',
            code: 'plan_dimension',
            event: 'planDimension',
            disabled: props.isDisabled
        },
        {
            label: '计划金额值',
            value: 'planAmount',
            type: 'number',
            show: true,
            precision: systemConfig.value.price_precision,
            max: 999999999999999,
        },
        {
            label: '计划范围',
            value: 'planRange',
            type: 'select-model',
            code: 'plan_range',
            event: 'planRange',
            disabled: props.isDisabled
        },
        {
            label: '范围值',
            value: 'rangeIdValue',
            type: 'slot',
            show: false
        },
        {
            label: '超量是否限制',
            value: 'isLimit',
            type: 'select-model',
            code: 'yes_or_no',
            event: 'isLimit',
            disabled: props.isDisabled
        },
        {
            label: '限制业务',
            value: 'limitBusiness',
            type: 'select-model',
            code: 'limit_business',
            show: true,
            disabled: props.isDisabled
        },
        {
            label: '临界是否提醒',
            value: 'isCriticalRemind',
            type: 'select-model',
            code: 'yes_or_no',
            event: 'isCriticalRemind',
            disabled: props.isDisabled
        },
        {
            label: '临界值(%)',
            value: 'criticalValue',
            type: 'number',
            max: 100,
            show: true,
            disabled: props.isDisabled
        },
        {
            label: '备注',
            value: 'remark',
            type: 'textarea',
        },
    ],
    rules: {
        planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
        planCycle: [{ required: true, message: '请选择计划周期', trigger: 'change' }],
        planYear: [{ required: true, message: '请选择年度', trigger: 'change' }],
        planQuarter: [{ required: true, message: '请选择季度', trigger: 'change' }],
        planMonth: [{ required: true, message: '请选择月度', trigger: 'change' }],
        planStartDate: [{ required: true, message: '请选择计划开始日期', trigger: 'change' }],
        planEndDate: [{ required: true, message: '请选择计划截止日期', trigger: 'change' }],
        planDimension: [{ required: true, message: '请选择计划维度', trigger: 'change' }],
        planAmount: [
            { required: true, message: '请输入计划金额值', trigger: 'blur' },
            { validator: proxy.$validate.positiveMoney, trigger: 'blur' },
        ],
        planRange: [{ required: true, message: '请选择计划范围', trigger: 'change' }],
        rangeIdValue: [{ required: true, message: '请选择范围值', trigger: 'change' }],
        isLimit: [{ required: true, message: '请选择超量是否限制', trigger: 'change' }],
        limitBusiness: [{ required: true, message: '请选择限制业务', trigger: 'change' }],
        isCriticalRemind: [{ required: true, message: '请选择临界是否提醒', trigger: 'change' }],
        criticalValue: [{ required: true, message: '请输入临界值', trigger: 'blur' }],
    },
    labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
    query: {
        purchPlanId: props.id
    },
    list: [
        { type: 'slot', value: 'addProduct' },
        { type: 'slot', value: 'removeProduct' },
    ],
})

// 表格相关
const tableInfo = ref({
    refresh: 1,
    initCurpage: 1,
    data: [],
    selections: [],
    summaryFieldList: [
        {
            value: 'planNumber',
            formatter: proxy.$fn.qtyFormatter,
        },
        {
            value: 'planAmount',
            formatter: proxy.$fn.TripartiteMethod,
        },
    ],
    fieldList: [
        { label: '产品名称', value: 'commonName' },
        { label: '产品编码', value: 'productCode' },
        { label: '产品规格', value: 'standard' },
        { label: '厂家名称', value: 'brandName' },
        { label: '库存单位', value: 'unitName' },
        { label: '计划数量', value: 'planNumber', type: 'slot' },
        { label: '计划金额', value: 'planAmount', type: 'slot' },
    ],
    handle: {
        fixed: 'right',
        label: '操作',
        width: '50',
        btList: [
            {
                label: '删除',
                popconfirmText: '删除后将改变数据,是否继续？',
                event: removeProduct,
                disabled: props.isDisabled,
                show: true,
            },
        ],
    },
})
//选择产品相关
const productInfo = ref({
    visible: false,
    tableKey:
        'purchPlanAddProduct-com.slip.spd.entity.vo.core.CoreProductVONew',
    query: {
        queryMap: {
            id: {
                queryType: 'NOT_IN',
                queryCategory: 'AND',
                value: '',
            },
            status: {
                queryType: 'EQUALS',
                queryCategory: 'AND',
                value: 1,
            },
            putShelfStatus: {
                asTbName: 'core_product_new',
                columnName: 'put_shelf_status',
                queryResource: 0,
                queryType: 'EQUALS',
                queryCategory: 'AND',
                value: 1,
            },
            type: {
                asTbName: 'core_product_new',
                columnName: 'type',
                queryResource: 0,
                queryType: 'EQUALS',
                queryCategory: 'AND',
                value: 0,
            },
        },
        queryParams: {},
    },
})
const selectDeptInfo = ref({
    visible: false,
    query: {
        deptAuth: 'id',
        status: 1,
        deptId: '',
    },
    checkedList: []
})
const showDialog = computed({
    get() {
        return props.visible
    },
    set(val) {
        emits('update:visible', val) // 更新父组件visible
    },
})
watch(
  () => tableInfo.value.data,
  (val) => {
   let planAmount = 0
    tableInfo.value.data.forEach((row) => {
        planAmount = proxy.$fn.accAdd(planAmount, row.planAmount || 0)
    })
    formInfo.value.data.planAmount = planAmount
  },
  { deep: true }
)
const canRemoveProduct = computed(() => {
    return tableInfo.value.selections.length
})

function changeHandle(e, val) {
    if (e === 'planCycle') {
        formInfo.value.data.isLimit = '1'
        formInfo.value.data.isCriticalRemind = '1'
        formInfo.value.data.planYear = undefined
        formInfo.value.data.planQuarter = ''
        formInfo.value.data.planMonth = ''
        formInfo.value.data.planStartDate = undefined
        formInfo.value.data.planEndDate = undefined
        formInfo.value.data.criticalValue = 80
        formInfo.value.fieldList.map(item => {
            if (item.value === 'planStartDate' || item.value === 'planEndDate') {
                item.disabled = true
            }
            if (item.value === 'isLimit' || item.value === 'isCriticalRemind') {
                item.disabled = false
            }
        })
        showFieldList('planStartDate', true)
        showFieldList('planEndDate', true)
        showFieldList('limitBusiness', true)
        showFieldList('criticalValue', true)
        switch (val) {
            case '1':
                showFieldList('planQuarter', false)
                showFieldList('planMonth', false)
                break;
            case '2':
                showFieldList('planQuarter', true)
                showFieldList('planMonth', false)
                break;
            case '3':
                showFieldList('planQuarter', false)
                showFieldList('planMonth', true)
                break;
            case '4':
                showFieldList('planQuarter', false)
                showFieldList('planMonth', false)
                showFieldList('planStartDate', false)
                showFieldList('planEndDate', false)
                formInfo.value.data.isLimit = '0'
                formInfo.value.data.isCriticalRemind = '0'
                showFieldList('limitBusiness', false)
                showFieldList('criticalValue', false)
                formInfo.value.data.criticalValue = undefined
                formInfo.value.fieldList.map(item => {
                    if (item.value === 'isLimit' || item.value === 'isCriticalRemind') {
                        item.disabled = true
                    }
                })
                break;
            case '5':
                showFieldList('planQuarter', false)
                showFieldList('planMonth', false)
                formInfo.value.fieldList.map(item => {
                    if (item.value === 'planStartDate' || item.value === 'planEndDate') {
                        item.disabled = false
                    }
                })
                break;
        }
    } else if (e === 'planYear') {
        formInfo.value.data.planQuarter = ''
        formInfo.value.data.planMonth = ''
        formInfo.value.data.planStartDate = undefined
        formInfo.value.data.planEndDate = undefined
        getDate()
    } else if (e === 'planQuarter') {
        getDate()
    } else if (e === 'planMonth') {
        getDate()
    } else if (e === 'planDimension') {
        formInfo.value.data.planAmount = undefined
        showFieldList('planAmount', val == '1')
        tableInfo.value.data = []
    } else if (e === 'planRange') {
        showFieldList('rangeIdValue', val == '2')
    } else if (e === 'isLimit') {
        formInfo.value.data.limitBusiness = val == '1' ? '1' : ''
        showFieldList('limitBusiness', val == '1')
        if(val == '0'){    
            formInfo.value.data.criticalValue = undefined
            formInfo.value.data.isCriticalRemind = '0'
        }
        showFieldList('criticalValue', val == '1' && formInfo.value.data.isCriticalRemind == '1')
        formInfo.value.fieldList.map(item => {
            if (item.value === 'isCriticalRemind') {
                item.disabled = val == '0'
            }
        })
        
    } else if (e === 'isCriticalRemind') {
        formInfo.value.data.criticalValue = val == '1' ? 80 : undefined
        showFieldList('criticalValue', val == '1')
    }
}
function getDate() {
    let data = formInfo.value.data
    if (data.planCycle == '1') {
        if (data.planYear) {
            formInfo.value.data.planStartDate = moment(data.planYear).startOf('year').format('YYYY-MM-DD')
            formInfo.value.data.planEndDate = moment(data.planYear).endOf('year').format('YYYY-MM-DD')
        }
    } else if (data.planCycle == '2') {
        if (data.planYear && data.planQuarter) {
            let year = data.planYear
            let quarter = Number(data.planQuarter)
            let startDate = moment().set({ year }); // 设置年份
            if (quarter > 1) {
                startDate.month((quarter - 1) * 3); // 设置月份
            } else {
                startDate.month(0); // 若是第一个季度，则从1月开始
            }
            startDate.date(1); // 设置日期为当月的第一天

            let endDate = startDate.clone(); // 克隆起始日期
            endDate.add(3, 'months').subtract(1, 'day'); // 将日期向后移动两个月，再减去一天得到结束日期
            formInfo.value.data.planStartDate = startDate.format('YYYY-MM-DD')
            formInfo.value.data.planEndDate = endDate.format('YYYY-MM-DD')
        }
    } else if (data.planCycle == '3') {
        if (data.planYear && data.planMonth) {
            let year = data.planYear
            let month = Number(data.planMonth)
            const startOfMonth = moment([year, month - 1])
            formInfo.value.data.planStartDate = startOfMonth.startOf('month').format('YYYY-MM-DD');
            formInfo.value.data.planEndDate = startOfMonth.endOf('month').format('YYYY-MM-DD');
        }
    }
}
function showFieldList(str, val) {
    formInfo.value.fieldList.map(item => {
        if (item.value === str) {
            item.show = val
        }
    })
}
function changeLargeAndAmount(e, str) {
    proxy.$refs.tableForm.clearValidate(str)
}
// 触发事件
function handleEvent(event, data) {
    switch (event) {
        case 'tableCheck':
            tableInfo.value.selections = [...data]
            break
    }
}
function selectDeptCallback(row) {
    if (row && row.length) {
        let names = row.map(item => item.name)
        let ids = row.map(item => item.id)
        formInfo.value.data['rangeIdValue'] = names.toString()
        formInfo.value.data['rangeId'] = ids.toString()
    } else {
        formInfo.value.data['rangeIdValue'] = ''
        formInfo.value.data['rangeId'] = ''
    }
}
function openDeptWindow() {
    selectDeptInfo.value.visible = true
}
function addProduct() {
    productInfo.value.query.queryMap.id.value = null
    //查询部门产品ids
    if (tableInfo.value.data.length) {
        productInfo.value.query.queryMap.id.value = tableInfo.value.data
            .map((item) => item.productId)
            .toString()
    }
    productInfo.value.visible = true
}

//删除产品
function removeProduct(selectRow = undefined) {
    if (selectRow && selectRow.productId) {
        tableInfo.value.data = tableInfo.value.data.filter(
            (row) => row !== selectRow
        )
    } else {
        proxy
            .$confirm('删除后将改变数据,是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
            .then(() => {
                tableInfo.value.data = tableInfo.value.data.filter(
                    (row) => !tableInfo.value.selections.includes(row)
                )
            })
    }
}
//选择产品
function selectProduct(data) {
    if (data && data.length ) {
        data.map( item =>{
            item.productId = item.id
            item.planNumber = null
            item.planAmount = null
        })
        tableInfo.value.data = data.concat(tableInfo.value.data)
    }
}
function saveAndSubmit(flowData){
    save(true, flowData)
}
function save(isSaveAndSubmit = false, obj = {}) {
    proxy.$fn.checkForm(formRefs.value).then(() => {
        const data = formInfo.value.data
            if(data.planDimension == '2'){
            if (!tableInfo.value.data.length) {
                proxy.$message({
                    duration: 3500,
                    type: 'warning',
                    showClose: true,
                    message: '请添加有效的产品',
                })
                return
            }
            let commonName = tableInfo.value.data.filter(item => item.planNumber <= 0 && item.planAmount <= 0).map(item => item.commonName)
            if(commonName && commonName.length){
                proxy.$message({
                    duration: 3500,
                    type: 'warning',
                    showClose: true,
                    message: `产品【${commonName}】的计划数量或计划金额未输入或输入不正确，请修改`,
                })
                return
            }
            data.details = tableInfo.value.data
        }
        let api = props.id ? updatePurchPlan : isSaveAndSubmit === true ? saveAndSubmitPurchPlan : createPurchPlan
        let paramsData = data
        // 如果是保存并提交
        if (isSaveAndSubmit) {
            if (proxy.$route.query.processInstanceId) {
                api = submitPurchPlan
            }
            paramsData = {
                orderData: data,
                // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
                flowTaskCommentDto: { approvalType: 'submit' },
                processDefinitionKey: 'purchPlan',
                processInstanceId: obj.processInstanceId,
                taskId: obj.taskId,
            }
        }
        
        api(paramsData).then((resp) => {
            if (resp && resp.success) {
                showDialog.value = false
                emits('returnModify', false)
            }
        })
    })
}
function getMain() {
    getPurchPlanById(props.id).then((resp) => {
        if (resp && resp.success) {
            formInfo.value.data = resp.data
            formInfo.value.fieldList.map(item => {
                if ( resp.data.planCycle == '4' && (item.value === 'planStartDate' || item.value === 'planEndDate')) {
                    item.disabled = props.isDisabled ? true : false
                }
                if ( resp.data.planCycle == '5' && (item.value === 'planStartDate' || item.value === 'planEndDate')) {
                    item.disabled = props.isDisabled ? true : false
                }
                if (resp.data.isLimit == '0' && (item.value === 'isCriticalRemind')) {
                    item.disabled = true
                }
            })
        
            showFieldList('planQuarter', resp.data.planCycle == '2')
            showFieldList('planMonth', resp.data.planCycle == '3')
            showFieldList('planStartDate', resp.data.planCycle !== '4')
            showFieldList('planEndDate', resp.data.planCycle !== '4')
            showFieldList('planAmount', resp.data.planDimension == '1')
            showFieldList('rangeIdValue', resp.data.planRange == '2')
            showFieldList('limitBusiness', resp.data.planCycle !== '4' && resp.data.isLimit == '1')
            showFieldList('criticalValue', resp.data.planCycle !== '4' && resp.data.isCriticalRemind == '1' && resp.data.isLimit == '1')
            if(resp.data.planRange == '2'){
                let ids = proxy.$fn.splitArr(resp.data.rangeId)
                if(ids && ids.length){
                    ids.map(item => {
                        selectDeptInfo.value.checkedList.push(Number(item))
                    })
                }else {
                    selectDeptInfo.value.checkedList = []
                }
            }
            if(resp.data.planDimension == '2'){
                getList()
            }
            
        }
    })
}
function getList() {
    getPurchProductDetail(filterInfo.value.query).then((res) => {
        if (res && res.success) {
            if(res.data && res.data.length){
                res.data.map(item => {
                    item.planNumber = item.planNumber ? parseFloat(item.planNumber) : null
                    item.planAmount = item.planAmount ? parseFloat(item.planAmount) : null
                })  
            }
            tableInfo.value.data = res.data
        }
    })
}


onMounted(() => {
    proxy.$nextTick(() => {
        formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
    })
    if (props.id) {
        getMain()
    }
})
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>
  
<style scoped lang="scss">
:deep(.table-scroll-hidden)>.el-table {
    overflow-y: hidden;
}
</style>
  